/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servidor.Controlador;

import Servidor.Modelo.Games.Game;
import Servidor.Modelo.Games.GameList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;

    
    
/**
 *
 * @author isabel
 * @author Jorge Perez
 */
class LeaveGameTask extends Thread implements OcaTask, Observer {

    private PrintWriter write;
    private BufferedReader read;
    private Socket socket;
    private int idGame;
    private int idPlayer;

    public LeaveGameTask (Socket socket, BufferedReader read, PrintWriter write) {
        this.write = write;
        this.socket = socket;
        this.read = read;
    }
 
      public void run() {
        String idGameString = null;
     
        int idUser = 1;
        String idPlayer = null;
        try {
            idPlayer = read.readLine();

        } catch (IOException ex) {
            System.out.println("Problemas al recibir la id del jugador que quiere dejar la partida");
        }
        try {
            idUser = Integer.parseInt(idPlayer);          
        } catch (NumberFormatException ex) {
            System.out.println("La id del jugador recibida no es un numero");
        }

        String idGame = null;
        int idGameInt = -100;

        try {
            idGame = read.readLine();

        } catch (IOException ex) {
            System.out.println("Problemas al recibir la id de la partida que quiere dejar");
        }
        try {
            idGameInt = Integer.parseInt(idGame);
            
        } catch (NumberFormatException ex) {
            System.out.println("La id de la partida recibida no es un numero");
        }
        Game game = GameList.getInstance().getGame(idGameInt);
        
        int isCorrect = game.remove_player_id(idUser);
        if(isCorrect == -1){
            System.out.println("Error al borrar el usuario");
            write.println("fail");
            
        }
//        game.deleteObserver(this);
        write.println(ConnectionConstraints.USER_DELETE_FROM_GAME);
    }

    @Override
    public void executeTask() {
        this.start();
    }

    @Override
    public void update(Observable o, Object arg) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
